import { useEffect, useRef, useState } from 'react';
import { LIMIT } from '@/constants/pageConstant.js';
import { Card, Flex, Form, Input, InputNumber } from 'antd';
import ModalUtil from '@/utils/modal.js';
import { CustomPage, CustomTable, StatusView } from '@/components/index.jsx';
import { SPACE } from '@/constants/themeConstant.js';
import { PermissionApi } from '@/api/permission/api.js';
import SearchForm from '@/components/SearchForm/index.jsx';
import PermissionFormModal from '@/pages/PermissionManage/widget/PermissionFormModal/index.jsx';
import YesNoIndicator from '@/components/YesNoIndicator/index.jsx';
import StringUtil from '@/utils/string.js';

// 表格选中项
const rowSelection = {
  type: 'checkbox',
  fixed: true,
  getCheckboxProps: (record) => {
    return {
      disabled: record?.isDefault === true
    };
  }
};

export default function PermissionManage() {
  // 表格
  const tableRef = useRef();
  // 搜索条件
  const [searchQuery, setSearchQuery] = useState();
  // 表单弹窗
  const formRef = useRef();

  useEffect(() => {
    if (searchQuery) {
      tableRef.current?.request();
    }
  }, [searchQuery]);

  // 请求数据
  async function getData(options) {
    // 解构条件
    const { pagination, sorter } = options;
    // 页码
    const pageNo = pagination?.current || 1;
    // 页大小
    const pageSize = pagination?.pageSize || LIMIT;
    // 排序字段
    const sortField = StringUtil.toSnakeCase(sorter?.field);
    // 排序方式
    const sortOrder = sorter?.order === 'ascend';
    const { code, data } = await PermissionApi.getList(
      pageNo,
      pageSize,
      searchQuery,
      sortField,
      sortOrder
    );
    const { list, total } = data;
    return Promise.resolve({
      data: list,
      success: code === 0,
      total: total
    });
  }

  function handleDelete(selectedRows) {
    if (selectedRows.length === 0) {
      ModalUtil.warn('请选择要删除的权限');
      return;
    }
    ModalUtil.confirm(
      `确定要删除: ${selectedRows.map((row) => row?.permissionName).join('、')} 吗？`,
      async () => {
        const ids = selectedRows.map((row) => row?.permissionId);
        await PermissionApi.deleteByIds(ids).then(({ code }) => {
          if (code === 0) {
            ModalUtil.success('删除成功');
            tableRef?.current?.request();
            tableRef.current?.setSelectedRows(
              tableRef.current?.selectedRows?.filter((row) => !ids.includes(row.permissionId))
            );
          }
        });
      }
    );
  }

  function onEdit(data) {
    formRef.current?.openEdit(data);
  }

  function onAdd() {
    formRef.current?.openAdd();
  }

  return (
    <CustomPage>
      <PermissionFormModal
        ref={formRef}
        onRefresh={() => {
          tableRef?.current?.request();
        }}
      />
      <Card>
        <Flex vertical gap={SPACE}>
          {renderToolbar()}
          <CustomTable
            ref={tableRef}
            rowKey="permissionId"
            title="权限列表"
            optionsWidth={45}
            onRowDelete={(row) => {
              handleDelete([row]);
            }}
            rowDeleteDisabled={(row) => {
              return row?.isDefault === true;
            }}
            onDelete={handleDelete}
            onAdd={onAdd}
            rowEditDisabled={(row) => {
              return row?.isDefault === true;
            }}
            onRowEdit={onEdit}
            onEdit={onEdit}
            rowSelection={rowSelection}
            columns={getColumns()}
            request={getData}
          />
        </Flex>
      </Card>
    </CustomPage>
  );

  // 渲染工具栏
  function renderToolbar() {
    const width = 150;
    return (
      <>
        <SearchForm
          onSearch={(values) => {
            tableRef.current?.setPageNo(1);
            setSearchQuery(values);
          }}
          formItems={
            <>
              <Form.Item label="权限ID" name="permissionId">
                <InputNumber min={1} placeholder="请输入权限ID" style={{ width: width }} />
              </Form.Item>
              <Form.Item label="权限名称" name="permissionName">
                <Input placeholder="请输入权限名称" style={{ width: width }} />
              </Form.Item>
              <Form.Item label="权限代码" name="permissionCode">
                <Input placeholder="请输入权限代码" style={{ width: width }} />
              </Form.Item>
            </>
          }
        />
      </>
    );
  }

  // 表格列
  function getColumns() {
    return [
      {
        title: '权限ID',
        dataIndex: 'permissionId',
        key: 'permissionId',
        sorter: true
      },
      {
        title: '权限名称',
        dataIndex: 'permissionName',
        key: 'permissionName'
      },
      {
        title: '权限代码',
        dataIndex: 'permissionCode',
        key: 'permissionCode'
      },
      {
        title: '权限说明',
        dataIndex: 'permissionDesc',
        key: 'permissionDesc'
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        render: (v) => {
          return <StatusView status={v} />;
        }
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        sorter: true
      },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
        key: 'updateTime',
        sorter: true
      },
      {
        title: '默认权限',
        dataIndex: 'isDefault',
        key: 'isDefault',
        render: (v) => {
          return <YesNoIndicator value={v} />;
        }
      }
    ];
  }
}
